package com.android.kotlincoroutinemvvmdemo.hook

import android.app.NotificationManager
import android.content.Context
import java.lang.reflect.Proxy

object HookNotificationManager {
    fun hook(context: Context) {
        try {
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE)
            val getService = NotificationManager::class.java.getDeclaredMethod("getService")
            getService.isAccessible = true
            val serviceInstance = getService.invoke(notificationManager)

            val notificationManagerClz = Class.forName("android.app.NotificationManager")
            val proxyNotificationManager = Proxy.newProxyInstance(
                javaClass.classLoader,
                arrayOf(notificationManagerClz)
            ) { _, method, args ->
                if (args != null && args.isNotEmpty()) {
                    for (argValue in args) {
                        //遍历参数  获取参数
                    }
                }
                //可以根据id或者tag筛选,进行不同的返回.
                method?.invoke(serviceInstance, *args.orEmpty()) //操作交由serviceInstance处理,不拦截通知.
                //null  返回null什么也不做
            }

            val serviceField = NotificationManager::class.java.getDeclaredField("sService")
            serviceField.isAccessible = true
            serviceField.set(notificationManager, proxyNotificationManager)
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }
}